"""
@Time : 2022/9/14 11:06
@Author : ls
@DES:
"""
import os
import numpy as np
from ctypes import *
import multiprocessing
from core.Response import *
from fastapi import APIRouter
from config import settings
from models.custom_class import CoalYard
from models.base_class import AutoYard
from models.sender_class import CloudSender
from fastapi import WebSocket, WebSocketDisconnect

router = APIRouter()
gCallbackFuncList = []
AutoYard_List: List[AutoYard] = []
Queue_List: List[multiprocessing.Queue] = []
# 雷达参数设置
RunMode = settings.RADAR.RUNMODE
Speed = settings.RADAR.SPEED
AngleSceneScan = settings.RADAR.ANGLESCENESCAN


def _callback(cid: c_uint, data_len: c_int, data, yard_id):
    auto_yard: AutoYard = get_yard(obj_id=yard_id)
    queue = auto_yard.get_queue()
    # queue = Queue_List[0]
    # coal_yard = AutoYard_List[0]
    code = int.from_bytes(data[2:4], byteorder='little', signed=True)

    if code == 3534:
        print("雷达连接成功, cid ====", cid)
    elif code == 3535:
        print("连接失败")
    elif code == 51108:
        print("运行模式设置成功")
    elif code == 118:
        points_data: bytes = data[54:data_len]
        queue.put(points_data)
        # cloud = {cid: points_data}
        # queue.put(cloud)

        # 判断雷达是否停止运行的条件
        last_line_flag = data[44]
        if last_line_flag == b'\x80':
            # 停止雷达并断开连接
            auto_yard.radar_stop(c_id=cid)
            # coal_yard.radar_stop(c_id=cid)
            print('雷达停止， cid ==== ', cid)
            queue.put('结束')

    return None


def get_yard(obj_id):
    for auto_yard in AutoYard_List:
        coal_id = id(auto_yard)
        coal_id = str(coal_id)
        coal_id = coal_id[:-6]
        coal_id = int(coal_id)
        if coal_id == obj_id:
            return auto_yard


def cloud_sender(coal_yard, queue):
    sender = CloudSender(coal_yard)
    sender.set_queue(queue=queue)
    # sender.set_websocket(websocket=websocket)
    while True:
        data = queue.get()
        if isinstance(data, bytes):
            print("当前进程号: %s" % os.getpid())
            cloud: np.ndarray = np.frombuffer(data, dtype=np.int16).reshape(-1, 3)
            print(cloud.size)
        elif data == '结束':
            break


@router.post(path="/coal_test", summary="数据产生者测试")
def invent_coal(coal_yard: CoalYard):
    queue = multiprocessing.Queue()
    Queue_List.append(queue)
    auto_yard = AutoYard(coal_yard=coal_yard)
    auto_yard.set_queue(queue=queue)
    AutoYard_List.append(auto_yard)
    auto_yard.sdk_init()
    yard_id = auto_yard.make_id()
    callback = auto_yard.set_callback_function(func=_callback, addr_id=yard_id)
    gCallbackFuncList.append(callback)
    auto_yard.radars_start_connect(wait_time=2)
    auto_yard.radars_rotate_begin(run_mode=RunMode, speed=Speed, angle_scan=AngleSceneScan)
    print("主进程号 == ", os.getpid())
    sender = multiprocessing.Process(target=cloud_sender, args=(coal_yard, queue,))
    sender.start()
    sender.join()
    print("=========主程序结束==========")
    print("子进程 == %s" % multiprocessing.active_children())
